﻿using System;
using System.Collections.Generic;
using System.Text;
using Cit.CDE.Net.Module;
using System.Resources;
using Cit.CDE.Net.Module.Commons;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using Cit.CDE.Net.Service;
using System.Data;
using Module;

namespace UserControl
{
    /// <summary>
    /// Copyright (C)   jinggubang
    /// FileName:        CommonPage.cs          
    /// Author :         mayb
    /// CDT:             2011-12-28        
    /// Version:         1.0.0.0               
    /// Depiction:       用户控件共同处理   
    /// </summary>
    public class UserControlsCommon : System.Web.UI.UserControl
    {
        public UserControlsCommon()
        {
            //
            //TODO: 在此处添加构造函数逻辑
            //
        }
        /// <summary>
        /// 错误标记
        /// </summary>
        private static string MUST_FLAG = "<font color=\"red\">*&nbsp;</font>";

        /// <summary>
        /// 页面设值
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="resouceManager"></param>
        protected void setControls(CDEEntity entity, ResourceManager resouceManager)
        {
            if (entity == null)
            {
                return;
            }

            string control_id = string.Empty;

            //遍历entity属性，设值到符合规则页面控件
            foreach (CDEAttribute attribute in entity.EntityManager.ListAttributes)
            {
                //是否显示
                if (CDEConstants.ConstDispType_NO_DISP.Equals(attribute.DISP_type))
                {
                    continue;
                }
                //是否隐藏
                else if (CDEConstants.ConstPointType_P_SOURCE.Equals(attribute.P_type))
                {
                    control_id = "hid_" + attribute.Name;
                }
                else if (CDEConstants.ConstPointType_P_TARGET.Equals(attribute.P_type))
                {
                    control_id = "ddl_" + attribute.Name;
                    if (this.FindControl(control_id) == null)
                    {
                        control_id = "txt_" + attribute.Name;
                    }
                }
                 
                else if (attribute.getP_Colmun().isHaveCandidate())
                {
                    control_id = "ddl_" + attribute.Name;
                    if (this.FindControl(control_id) == null)
                    {
                        control_id = "cbl_" + attribute.Name;
                    }
                }

                //string
                else if (ConstDataType.STRING.Equals(attribute.getP_Colmun().Type))
                {
                    control_id = "txt_" + attribute.Name;
                }
                //Number
                else if (ConstDataType.NUMBER.Equals(attribute.getP_Colmun().Type))
                {
                    control_id = "txt_" + attribute.Name;
                }

                //bool ddl
                else if (ConstDataType.BOOLEAN.Equals(attribute.getP_Colmun().Type))
                {
                    control_id = "ddl_" + attribute.Name;
                }

                //Img
                else if (ConstDataType.IMAGE.Equals(attribute.getP_Colmun().Type))
                {
                    control_id = "txt_" + attribute.Name;
                }

                //File
                else if (ConstDataType.FILE.Equals(attribute.getP_Colmun().Type))
                {
                    control_id = "txt_" + attribute.Name;
                }

                //Date
                else if (ConstDataType.DATE.Equals(attribute.getP_Colmun().Type))
                {
                    control_id = "txt_" + attribute.Name;
                }

                else
                {
                    control_id = "txt_" + attribute.Name;
                }

                //查找页面控件
                Control control = this.FindControl(control_id);
                if (control != null)
                {
                    //是否必填
                    Label must_lab = (Label)this.FindControl("lbl_" + attribute.Name);
                    if (must_lab != null)
                    {
                        if (attribute.getSAttribute() == null)
                        {
                            if (attribute.Is_not_null == "1")
                            {
                                if (must_lab.Text.IndexOf(MUST_FLAG) != 0)
                                {
                                    must_lab.Text = MUST_FLAG + must_lab.Text;
                                }
                            }
                        }
                        else
                        {
                            CDEAttribute s_attribute = attribute.getSAttribute();
                            while (s_attribute.getSAttribute() != null)
                            {
                                s_attribute = s_attribute.getSAttribute();
                            }
                            if (s_attribute.Is_not_null == "1")
                            {
                                if (must_lab.Text.IndexOf(MUST_FLAG) != 0)
                                {
                                    must_lab.Text = MUST_FLAG + must_lab.Text;
                                }
                            }
                        }
                    }

                    //错误信息
                    Label lab = (Label)this.FindControl("err_" + attribute.Name);
                    if (lab != null)
                    {
                        if (entity.AttributeErrors.ContainsKey(attribute.Name))
                        {
                            lab.Text = "&nbsp;<font color=\"red\">"
                                + getErrMsg(resouceManager, attribute, entity.AttributeErrors[attribute.Name]) + "</font>";
                        }
                        else
                        {
                            lab.Text = string.Empty;
                        }
                    }


                    if (control_id.StartsWith("hid_"))
                    {
                        //((HiddenField)control).Value = EntityWithXml.getObject2String();
                        ((HiddenField)control).Value = StringWithXml.getObject2String(entity.get(attribute));
                    }
                    else if (control_id.StartsWith("ddl_"))
                    {
                        //CheckBox
                        if (Convert.ToString(control).Trim().EndsWith("CheckBox"))
                        {
                            CheckBox ddl = (CheckBox)control;

                            ddl.Checked = false;
                            object o = entity.get(attribute.Name);
                            if (entity.get(attribute.Name) != null && entity.get(attribute.Name).ToString() == "1")
                            {
                                ddl.Checked = true;
                            }
                        }
                        //RadioButtonList
                        else if (Convert.ToString(control).Trim().EndsWith("RadioButtonList"))
                        {
                            RadioButtonList ddl = (RadioButtonList)control;

                            string defaultOption = ddl.Attributes["DefaultOption"];

                            ddl.Items.Clear();

                            CDEColumn clm = attribute.getP_Colmun();

                            foreach (CDECandidate cndt in clm.getCandidates())
                            {
                                ListItem item = new ListItem();

                                item.Text = cndt.Label;

                                item.Value = cndt.Value;

                                ddl.Items.Add(item);

                                if (cndt.Value == defaultOption)
                                {
                                    ddl.ClearSelection();

                                    item.Selected = true;
                                }
                            }
                            foreach (ListItem item in ddl.Items)
                            {

                                if (entity.get(attribute.Name) != null && entity.get(attribute.Name).ToString() == item.Value)
                                {
                                    ddl.ClearSelection();

                                    item.Selected = true;
                                }
                            }
                        }
                        else
                        {
                            //DropDownList
                            DropDownList ddl = (DropDownList)control;

                            bool defaultSelect = false;
                            if (!CDEConstants.IsEmpty(entity.get(attribute.Name)))
                            {
                                defaultSelect = true;
                            }
                            if (ddl.Items.Count > 0)
                            {
                                ddl.ClearSelection();
                                ddl.Items[0].Selected = true;
                                if (!defaultSelect)
                                {
                                    continue;
                                }

                                foreach (ListItem item in ddl.Items)
                                {

                                    if (item.Text == StringWithXml.getObject2String(entity.get(attribute.Name)) || item.Value == StringWithXml.getObject2String(entity.get(attribute.Name)))
                                    {
                                        ddl.ClearSelection();
                                        item.Selected = true;
                                    }
                                }
                            }
                            else
                            {
                                if (lab.Text.IndexOf(MUST_FLAG) == -1)
                                {
                                    ddl.Items.Add(new ListItem("", ""));
                                }
                                if (attribute.getP_Colmun().isHaveCandidate())
                                {
                                    CDEColumn clm = attribute.getP_Colmun();
                                    foreach (CDECandidate cndt in clm.getCandidates())
                                    {
                                        ListItem item = new ListItem();
                                        item.Text = cndt.Label;
                                        item.Value = cndt.Value;
                                        ddl.Items.Add(item);
                                        if (defaultSelect
                                            && cndt.Value == StringWithXml.getObject2String(entity.get(attribute.Name)))
                                        {
                                            ddl.ClearSelection();
                                            item.Selected = true;
                                            //ddl.SelectedItem = item;
                                        }
                                    }
                                }
                                else if (CDEConstants.ConstPointType_P_TARGET.Equals(attribute.P_type))
                                {
                                    //参照对象列名
                                    string canzhao = ddl.Attributes["CanZhao"];

                                    CDEAttribute s_attribute = attribute.getSAttribute();

                                    while (s_attribute.getSAttribute() != null)
                                    {
                                        s_attribute = s_attribute.getSAttribute();
                                    }

                                    iEntityManager iem = CDEEMServiceFactory.getEMService(attribute.EntityManager);
                                    
                                    CDESearchCriteria sc = iem.CreateSearchCriteria();

                                    string tiaojian = ddl.Attributes["TiaoJian"];

                                    if (tiaojian != null && tiaojian != "") 
                                    {
                                        string[] defs = tiaojian.Split('#');

                                        foreach (string str in defs)
                                        {
                                            string[] def = str.Split('|');

                                            if (def[2] == "1")
                                            {
                                                sc.addCondition(def[0], def[1], CDEConstCompare.GreaterThan);
                                            }
                                            else if (def[2] == "2")
                                            {
                                                sc.addCondition(def[0], def[1], CDEConstCompare.LessThan);
                                            }
                                            else if (def[2] == "3")
                                            {
                                                sc.addCondition(def[0], def[1]);
                                            }
                                            else if (def[2] == "4")
                                            {
                                                sc.addCondition(def[0], def[1], CDEConstCompare.LikeLeft);
                                            }
                                        }
                                    }

                                    DataTable dt = iem.LoadEditPoints(attribute, sc);

                                    foreach (DataRow row in dt.Rows)
                                    {
                                        ListItem item = new ListItem();

                                        if (canzhao != null)
                                        {
                                            item.Text = row[canzhao].ToString();
                                        }
                                        else
                                        {

                                            item.Text = row["NAME"].ToString();
                                        }
                                        item.Value = row["CDE_DATAROW_ID"].ToString();

                                        ddl.Items.Add(item);

                                        if (defaultSelect
                                            && row["CDE_DATAROW_ID"].ToString() == entity.get(s_attribute.Name).ToString())
                                        {
                                            ddl.ClearSelection();
                                            item.Selected = true;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else if (control_id.StartsWith("cbl_"))
                    {
                        if (Convert.ToString(control).Trim().EndsWith("CheckBoxList"))
                        {
                            CheckBoxList cbl = (CheckBoxList)control;

                            string defaultOption = cbl.Attributes["DefaultOption"];

                            cbl.Items.Clear();
                           
                            CDEColumn clm = attribute.getP_Colmun();

                            foreach (CDECandidate cndt in clm.getCandidates())
                            {
                                ListItem item = new ListItem();

                                item.Text = cndt.Label;

                                item.Value = cndt.Value;

                                cbl.Items.Add(item);

                                if (defaultOption != null && defaultOption != "")
                                {
                                    string[] defaultOptions = defaultOption.Split('|');

                                    foreach (string str in defaultOptions)
                                    {
                                        if (cndt.Value == str)
                                        {
                                            item.Selected = true;

                                            break;
                                        }

                                    }
                                }
                            }
                            if (entity.get(attribute.Name) != null && entity.get(attribute.Name).ToString() != "")
                            {
                                string[] values = entity.get(attribute.Name).ToString().Split('|');

                                foreach (ListItem item in cbl.Items)
                                {

                                    foreach (string str in values)
                                    {
                                       if (item.Value == str)
                                       {
                                          item.Selected = true;

                                          break;
                                       }
                                   }
                                }
                            }
                        }
                    }
                    else
                    {
                        ((TextBox)control).Text = StringWithXml.getObject2String(entity.get(attribute.Name));
                    }

                    HiddenField checkId = (HiddenField)this.FindControl("hidCheckId");
                    if (checkId != null && entity.Result != CDEDataOperationResult.ERROR)
                    {
                        checkId.Value = entity.Id;
                    }
                    HiddenField selectId = (HiddenField)this.FindControl("hidSelectId");
                    if (selectId != null)
                    {
                        selectId.Value = "";
                    }
                }
                else
                {
                    control_id = "LBL_T_" + attribute.Name;
                    control = this.FindControl(control_id);
                    if (control != null)
                    {
                        if (entity.EntityManager.getAttribute(attribute.Name).getP_Colmun().isHaveCandidate())
                        {
                            if (entity.get(attribute.Name) != null)
                            {
                                ((Label)control).Text =
                                    StringWithXml.getObject2String(entity.EntityManager.getAttribute(attribute.Name).getP_Colmun().getCandidateLable(entity.get(attribute.Name).ToString()));
                            }
                        }
                        else
                        {
                            ((Label)control).Text = StringWithXml.getObject2String(entity.get(attribute.Name));
                        }
                    }
                }

            }
        }

        /// <summary>
        /// 取页面值构造Entity
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="request"></param>
        protected void setEntityFromRequest(CDEEntity entity, NameValueCollection request,string uc_Name)
        {
            if (entity == null)
            {
                return;
            }
            string control_id = string.Empty;

            foreach (CDEAttribute attribute in entity.EntityManager.ListAttributes)
            {
                if (CDEConstants.ConstDispType_NO_DISP.Equals(attribute.DISP_type))
                {
                    continue;
                }

                else if (CDEConstants.ConstPointType_P_SOURCE.Equals(attribute.P_type))
                {
                    control_id = "hid_" + attribute.Name;
                }
                else if (CDEConstants.ConstPointType_P_TARGET.Equals(attribute.P_type))
                {
                    control_id = "ddl_" + attribute.Name;
                    if (this.FindControl(control_id) == null)
                    {
                        control_id = "txt_" + attribute.Name;
                    }
                }

                else if (attribute.getP_Colmun().isHaveCandidate())
                {
                    control_id = "ddl_" + attribute.Name;
                }

                //string
                else if (ConstDataType.STRING.Equals(attribute.getP_Colmun().Type))
                {
                    control_id = "txt_" + attribute.Name;
                }
                //Number
                else if (ConstDataType.NUMBER.Equals(attribute.getP_Colmun().Type))
                {
                    control_id = "txt_" + attribute.Name;
                }

                //bool ddl
                else if (ConstDataType.BOOLEAN.Equals(attribute.getP_Colmun().Type))
                {
                    control_id = "ddl_" + attribute.Name;
                }

                //Img
                else if (ConstDataType.IMAGE.Equals(attribute.getP_Colmun().Type))
                {
                    control_id = "txt_" + attribute.Name;
                }

                //File
                else if (ConstDataType.FILE.Equals(attribute.getP_Colmun().Type))
                {
                    control_id = "txt_" + attribute.Name;
                }

                //Date
                else if (ConstDataType.DATE.Equals(attribute.getP_Colmun().Type))
                {
                    control_id = "txt_" + attribute.Name;
                }

                else
                {
                    control_id = "txt_" + attribute.Name;
                }               
                Control control = this.FindControl(control_id);
                string value = request[uc_Name + "$" + control_id];
                if (CDEConstants.IsEmpty(value))
                {
                    if (control != null)
                    {
                        if (Convert.ToString(control).Trim().EndsWith("DropDownList"))
                        {
                            DropDownList ddl = (DropDownList)control;

                            string canzhao = ddl.Attributes["CanZhao"];

                            if (canzhao != "" && canzhao != null)
                            {

                                CDEAttribute s_attribute = attribute.getSAttribute();
                                entity.set(attribute, null);
                                while (s_attribute.getSAttribute() != null)
                                {
                                    entity.set(s_attribute, null);
                                    s_attribute = s_attribute.getSAttribute();
                                }
                                entity.set(s_attribute, value);
                            }
                            else {
                                entity.set(attribute, null);
                            }
                        }
                        else if (Convert.ToString(control).Trim().EndsWith("CheckBox"))
                        {
                            entity.set(attribute, false);
                        }
                        else
                        {
                            entity.set(attribute, null);
                        }
                    }
                }
                else
                {
                    if (CDEConstants.ConstPointType_P_TARGET.Equals(attribute.P_type))
                    {
                      if (control_id.StartsWith("ddl_"))
                        {

                            CDEAttribute s_attribute = attribute.getSAttribute();
                            entity.set(attribute, null);
                            while (s_attribute.getSAttribute() != null)
                            {
                                entity.set(s_attribute, null);
                                s_attribute = s_attribute.getSAttribute();
                            }
                            entity.set(s_attribute, value);

                        }
                        else
                        {
                            entity.set(attribute, value);
                        }
                    }
                    else if (CDEConstants.ConstDispType_DISP.Equals(attribute.P_type))
                    {

                        if (value != null && Convert.ToString(control).Trim().EndsWith("CheckBox"))
                        {

                            entity.set(attribute, true);
                        }
                        else
                        {
                            entity.set(attribute, value);
                        }
                    }
                    else
                    {
                        entity.set(attribute, value);
                    }
                }
            }

            HiddenField checkId = (HiddenField)this.FindControl("hidCheckId");
            if (checkId != null)
            {
                if (CDEConstants.IsEmpty(checkId.Value))
                {
                    HiddenField selectId = (HiddenField)this.FindControl("hidSelectId");
                    if (selectId != null)
                    {
                        entity.Id = selectId.Value;
                    }
                }
                else
                {
                    entity.Id = checkId.Value;
                }
            }
        }

        /// <summary>
        /// 错误信息
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="attribute"></param>
        /// <param name="errCode"></param>
        /// <returns></returns>
        private string getErrMsg(ResourceManager manager, CDEAttribute attribute, string errCode)
        {
            if (manager == null)
            {
                return errCode;
            }
            string msg = manager.GetString(errCode);
            if (CDEConstants.IsEmpty(msg))
            {
                return errCode;
            }

            StringBuilder sbr = new StringBuilder();
            if ("ERR_NOT_DEFINED_POINTER".Equals(errCode)
                || "ERR_DUPLICATE_POINTER".Equals(errCode)
                || "ERR_NOT_FOUND_REFERENCE_DATA".Equals(errCode))
            {
                sbr.AppendFormat(msg, attribute.getSAttribute().Label);
            }
            else if ("ERR_UNABLE_TO_FIND_TEXT".Equals(errCode)
                || "ERR_ISNOTNULL_NOT_ENTER".Equals(errCode)
                || "ERR_UKEY_EXIST".Equals(errCode)
                || "ERR_UKEY_NULL".Equals(errCode))
            {
                sbr.AppendFormat(msg, attribute.Label);
            }
            else if ("ERR_CANNOT_MODIFY_COLUMN_LENGTH".Equals(errCode))
            {
                sbr.AppendFormat(msg, attribute.getP_Colmun().F_len);
            }
            else
            {
                sbr.Append(msg);
            }
            return sbr.ToString();
        }

        /// <summary>
        /// 把信息alert到画面上
        /// </summary>
        /// <param name="msg">信息内容</param>
        protected  void showMsgForHtml(string msg)
        {
            StringBuilder sbr = new StringBuilder();
            sbr.AppendFormat("<script language=\"javascript\">{0}", Environment.NewLine);
            sbr.AppendFormat("alert(\"");
            sbr.AppendFormat(msg);
            sbr.AppendFormat("\");</script>{0}", Environment.NewLine);
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "Startup", sbr.ToString());
        }
        /// <summary>
        /// 把联动下拉单中的选择值处理一下只剩下code
        /// </summary>
        /// <param name="codeAndName">处理前</param>
        /// <returns>处理后</returns>
        protected  string cutCodeFromCodeAndName(string codeAndName)
        {
            string result = "";
            int index = codeAndName.IndexOf(":");
            if (index > 0)
            {
                result = codeAndName.Substring(0, index);
            }
            return result;
        }


        /// <summary>
        /// 调用前台js ,用js再调用后台
        /// </summary>
        protected void refrashPageJS(string jsMethod)
        {
            StringBuilder sbr = new StringBuilder();
            sbr.AppendFormat("<script language=\"javascript\">{0}", Environment.NewLine);
            sbr.AppendFormat("{0}();", jsMethod);           
            sbr.AppendFormat("</script>{0}", Environment.NewLine);
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "Startup", sbr.ToString());
        }

        /// <summary>
        /// 执行用户控件中的方法
        /// </summary>
        protected void refrashDunInfoList()
        {
            //取得用户控件的信息
            System.Web.UI.Control u = Parent.Page.FindControl("uc_DunInfo_Manager");
            if (u != null)
            {

                //取得用户控件的类型
                Type t = Parent.Page.FindControl("uc_DunInfo_Manager").GetType();

                //得到用户控件中要调用的方法
                System.Reflection.MethodInfo m = t.GetMethod("refrashList");
                //执行方法
                m.Invoke(u, new object[0]);
            }
        }

        /// <summary>
        /// 更改数据库中SEQ的最大值
        /// </summary>
        public bool updateseq(string tableName)
        {
            string sql = "select max(ID) from " + tableName;
            string IDMax = Util.ExcuteScaler(sql, CommandType.Text, null);
            if (IDMax.Equals(""))
            {
                IDMax = "0";
            }
            string sqls = string.Format("update dbo.m_id_index_tbl set id_index='{0}'where name='" + tableName + "'", IDMax);
            bool flag = Util.ExcuteNonQuery(sqls, CommandType.Text, null);
            return flag;
        }
    }
}
